/*
 * To change this template, choose Tools | Templates
 * and open the template in the editor.
 */

/*
 * ServiceRequestForm.java
 *
 * Created on 26-Jul-2011, 16:30:01
 */
package GUI;

import java.awt.event.*;
import utilities.MessageDialog;
import java.sql.*;
import java.util.logging.Level;
import java.util.logging.Logger;
import javax.swing.JOptionPane;
import sql.Connector;
import utilities.FixedQueries;
import utilities.IDCreator;
import utilities.TableParser;

/**
 *
 * @author Alex Hughes
 */
public class GroupContactFrame extends GUI {

    private GUI previousFrame;
    private Connector connector;
    private int groupID;

    /** Creates new form ServiceRequestForm */
    public GroupContactFrame(GUI aPreviousFrame, Connector aConnector, int aGroupID) {
        previousFrame = aPreviousFrame;
        connector = aConnector;
        groupID = aGroupID;

        initComponents();

        this.addWindowListener(new WindowAdapter() {

            public void windowClosing(WindowEvent e) {
                backButton();
            }
        });

        try {
            reloadInfoTable();
        } catch (SQLException ex) {
            MessageDialog.conError(this);
            Logger.getLogger(GroupContactFrame.class.getName()).log(Level.SEVERE, null, ex);
        }

        super.setFrameLocationCenter(this);
        this.setVisible(true);
    }

    /** This method is called from within the constructor to
     * initialize the form.
     * WARNING: Do NOT modify this code. The content of this method is
     * always regenerated by the Form Editor.
     */
    // <editor-fold defaultstate="collapsed" desc="Generated Code">//GEN-BEGIN:initComponents
    private void initComponents() {

        jPanel1 = new javax.swing.JPanel();
        jScrollPane1 = new javax.swing.JScrollPane();
        relatedContactTable = new javax.swing.JTable();
        jScrollPane2 = new javax.swing.JScrollPane();
        unrelatedContactTable = new javax.swing.JTable();
        newContactBtn = new javax.swing.JButton();
        delCorrelationBtn = new javax.swing.JButton();
        viewContactBtn = new javax.swing.JButton();
        backBtn = new javax.swing.JButton();
        correlateBtn = new javax.swing.JButton();
        delContactBtn = new javax.swing.JButton();

        setDefaultCloseOperation(javax.swing.WindowConstants.DISPOSE_ON_CLOSE);
        addWindowListener(new java.awt.event.WindowAdapter() {
            public void windowClosing(java.awt.event.WindowEvent evt) {
                exitForm(evt);
            }
        });

        jScrollPane1.setBorder(javax.swing.BorderFactory.createTitledBorder("Correlated Contacts"));

        relatedContactTable.setModel(new javax.swing.table.DefaultTableModel(
            new Object [][] {

            },
            new String [] {

            }
        ));
        jScrollPane1.setViewportView(relatedContactTable);

        jScrollPane2.setBorder(javax.swing.BorderFactory.createTitledBorder("All Contacts"));

        unrelatedContactTable.setModel(new javax.swing.table.DefaultTableModel(
            new Object [][] {

            },
            new String [] {

            }
        ));
        jScrollPane2.setViewportView(unrelatedContactTable);

        javax.swing.GroupLayout jPanel1Layout = new javax.swing.GroupLayout(jPanel1);
        jPanel1.setLayout(jPanel1Layout);
        jPanel1Layout.setHorizontalGroup(
            jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGroup(javax.swing.GroupLayout.Alignment.TRAILING, jPanel1Layout.createSequentialGroup()
                .addComponent(jScrollPane1, javax.swing.GroupLayout.DEFAULT_SIZE, 528, Short.MAX_VALUE)
                .addGap(18, 18, 18)
                .addComponent(jScrollPane2, javax.swing.GroupLayout.DEFAULT_SIZE, 529, Short.MAX_VALUE))
        );
        jPanel1Layout.setVerticalGroup(
            jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addComponent(jScrollPane1, javax.swing.GroupLayout.DEFAULT_SIZE, 466, Short.MAX_VALUE)
            .addComponent(jScrollPane2, javax.swing.GroupLayout.DEFAULT_SIZE, 466, Short.MAX_VALUE)
        );

        newContactBtn.setText("New Contact");
        newContactBtn.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                newContactBtnActionPerformed(evt);
            }
        });

        delCorrelationBtn.setText("Delete Correlation");
        delCorrelationBtn.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                delCorrelationBtnActionPerformed(evt);
            }
        });

        viewContactBtn.setText("View Contact");
        viewContactBtn.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                viewContactBtnActionPerformed(evt);
            }
        });

        backBtn.setText("<Back");
        backBtn.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                backBtnActionPerformed(evt);
            }
        });

        correlateBtn.setText("Correlate");
        correlateBtn.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                correlateBtnActionPerformed(evt);
            }
        });

        delContactBtn.setText("Delete Contact");
        delContactBtn.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                delContactBtnActionPerformed(evt);
            }
        });

        javax.swing.GroupLayout layout = new javax.swing.GroupLayout(getContentPane());
        getContentPane().setLayout(layout);
        layout.setHorizontalGroup(
            layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGroup(layout.createSequentialGroup()
                .addContainerGap()
                .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
                    .addComponent(jPanel1, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)
                    .addGroup(layout.createSequentialGroup()
                        .addComponent(backBtn, javax.swing.GroupLayout.PREFERRED_SIZE, 82, javax.swing.GroupLayout.PREFERRED_SIZE)
                        .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.UNRELATED)
                        .addComponent(viewContactBtn)
                        .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.UNRELATED)
                        .addComponent(delCorrelationBtn)
                        .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED, 390, Short.MAX_VALUE)
                        .addComponent(correlateBtn)
                        .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.UNRELATED)
                        .addComponent(delContactBtn)
                        .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.UNRELATED)
                        .addComponent(newContactBtn)))
                .addContainerGap())
        );
        layout.setVerticalGroup(
            layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGroup(javax.swing.GroupLayout.Alignment.TRAILING, layout.createSequentialGroup()
                .addContainerGap()
                .addComponent(jPanel1, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)
                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.UNRELATED)
                .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
                    .addComponent(backBtn)
                    .addComponent(delCorrelationBtn)
                    .addComponent(viewContactBtn)
                    .addComponent(newContactBtn)
                    .addComponent(delContactBtn)
                    .addComponent(correlateBtn))
                .addContainerGap())
        );

        pack();
    }// </editor-fold>//GEN-END:initComponents

    /** Exit the Application */
    private void exitForm(java.awt.event.WindowEvent evt) {//GEN-FIRST:event_exitForm
        backButton();
    }//GEN-LAST:event_exitForm

    private void viewContactBtnActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_viewContactBtnActionPerformed
        editContactButton();
    }//GEN-LAST:event_viewContactBtnActionPerformed

    private void delCorrelationBtnActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_delCorrelationBtnActionPerformed
        deleteContactButton(false);
    }//GEN-LAST:event_delCorrelationBtnActionPerformed

    private void newContactBtnActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_newContactBtnActionPerformed
        newContactButton();
    }//GEN-LAST:event_newContactBtnActionPerformed

    private void backBtnActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_backBtnActionPerformed
        backButton();
    }//GEN-LAST:event_backBtnActionPerformed

private void correlateBtnActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_correlateBtnActionPerformed
    correlateContactButton();
}//GEN-LAST:event_correlateBtnActionPerformed

private void delContactBtnActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_delContactBtnActionPerformed
    deleteContactButton(true);
}//GEN-LAST:event_delContactBtnActionPerformed
    /**
     * @param args the command line arguments
     */
    // Variables declaration - do not modify//GEN-BEGIN:variables
    private javax.swing.JButton backBtn;
    private javax.swing.JButton correlateBtn;
    private javax.swing.JButton delContactBtn;
    private javax.swing.JButton delCorrelationBtn;
    private javax.swing.JPanel jPanel1;
    private javax.swing.JScrollPane jScrollPane1;
    private javax.swing.JScrollPane jScrollPane2;
    private javax.swing.JButton newContactBtn;
    private javax.swing.JTable relatedContactTable;
    private javax.swing.JTable unrelatedContactTable;
    private javax.swing.JButton viewContactBtn;
    // End of variables declaration//GEN-END:variables

    @Override
    public void reloadInfoTable() throws SQLException {

        TableParser.fillTable("" //filling the related Table
                + "SELECT c.* "
                + "FROM Contact c "
                + "INNER JOIN ContactGroup cg ON c.ContactID = cg.ContactID "
                + "INNER JOIN cGroup g ON g.cGroupID = cg.GroupID "
                + "WHERE g.cGroupID = " + groupID, relatedContactTable, connector);

        TableParser.fillTable(""
                + "SELECT * "
                + "FROM Contact c "
                + "WHERE c.ContactID NOT IN (SELECT cg.ContactID "
                + "                          FROM ContactGroup cg "
                + "                          WHERE cg.GroupID = " + groupID + ") "
                , unrelatedContactTable, connector);
                                                
    }

    private void editContactButton() {
        int requestID = TableParser.checkRowsAndGetID(relatedContactTable, this);

        if (requestID != -1) {
            new ContactFrame(this, connector, requestID);

        }
    }
    
    //the boolean var is used to determine whether the correlation or the contact will be deleted
    private void deleteContactButton(boolean isDeleteContact) {
        int contactID = -1;

        if (isDeleteContact) {
            contactID = TableParser.checkRowsAndGetID(unrelatedContactTable, this);
        } else {
            contactID = TableParser.checkRowsAndGetID(relatedContactTable, this);
        }

        if (contactID != -1) {
            int answer = MessageDialog.deleteQuestion(this);
            if (answer == JOptionPane.YES_OPTION) {
                try {
                    connector.sendUpdate(""
                            + "DELETE FROM ContactGroup "
                            + "WHERE ContactID = " + contactID + " AND GroupID = " + groupID);
                    if (isDeleteContact) {
                        FixedQueries.deleteContact(connector, contactID);
                    }
                    reloadInfoTable();
                } catch (SQLException ex) {
                    MessageDialog.conError(this);
                    Logger.getLogger(GroupContactFrame.class.getName()).log(Level.SEVERE, null, ex);
                }
            }
        }
    }

    private void correlateContactButton() {
        int contactID = TableParser.checkRowsAndGetID(unrelatedContactTable, this);
        int contactGroupID;
        
        if (contactID != -1) {
            try {
                contactGroupID = IDCreator.createID(connector, "ContactGroup");
                connector.sendUpdate(""
                        + "INSERT INTO `ContactGroup` (`ContactGroupID`, `GroupID`, `ContactID`) VALUES "
                        + "(" + contactGroupID + ", " + groupID + ", " + contactID + ") ");
                reloadInfoTable();
            } catch (SQLException ex) {
                MessageDialog.correlationError(this);
                Logger.getLogger(GroupContactFrame.class.getName()).log(Level.SEVERE, null, ex);
            }
        }

    }

    private void newContactButton() {
        new ContactFrame(this, connector);
        this.setVisible(false);
    }

    private void backButton() {
        previousFrame.setVisible(true);
        this.dispose();
    }
}
